package com.bittech.chatroom.dao;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.bittech.chatroom.util.CommUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @Author: yuisama
 * @Date: 2019-06-18 15:37
 * @Description:封装数据源连接、关闭资源等基础操作
 */
public class BaseDao {
    private static DruidDataSource dataSource;

    static {
        try {
            dataSource = (DruidDataSource) DruidDataSourceFactory
                    .createDataSource(CommUtils.loadProperties("db.properties"));
        } catch (Exception e) {
            System.err.println("数据源加载失败");
        }
    }

    protected DruidPooledConnection getConnection(boolean isAutoCommit) throws SQLException {
        DruidPooledConnection connection = dataSource.getConnection();
        connection.setAutoCommit(isAutoCommit);
        return connection;
    }

    protected void closeResources(Statement statement, ResultSet resultSet, DruidPooledConnection connection) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

